package com.anta.it.hr.devtools.core.request.impl;

import com.anta.it.hr.devtools.core.request.RequestInetAddress;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 从请求对象中获取ip信息
 * @author wangxiaoxian
 * @since 2021/8/4
 */
@Slf4j
public abstract class AbstractRequestInetAddress implements RequestInetAddress {

    public String getIp(Object loadBalanceKey) {
        String ipAddress = getIpFromHeader("x-forwarded-for", loadBalanceKey);
        log.info("x-forwarded-for, {}", ipAddress);
        if (StringUtils.isBlank(ipAddress) || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = getIpFromHeader("Proxy-Client-IP", loadBalanceKey);
            log.info("Proxy-Client-IP, {}", ipAddress);
        }
        if (StringUtils.isBlank(ipAddress) || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = getIpFromHeader("WL-Proxy-Client-IP", loadBalanceKey);
            log.info("WL-Proxy-Client-IP, {}", ipAddress);
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > 15 && ipAddress.contains(",")) { //"***.***.***.***".length() = 15
            ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            log.info("multi-layer proxy, get first one:{}", ipAddress);
        }
        if (ipAddress == null || ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
            ipAddress = getRemoteIp(loadBalanceKey);
            log.info("local RemoteIp:{}", ipAddress);
        }
        if ("127.0.0.1".equals(ipAddress) || "0:0:0:0:0:0:0:1".equals(ipAddress)) {
            //根据网卡取本机配置的IP
            InetAddress inet = null;
            try {
                inet = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                e.printStackTrace();
                return null;
            }
            ipAddress = inet.getHostAddress();
            log.info("Local network card:{}", ipAddress);
        }
        return ipAddress;
    }

    public abstract String getIpFromHeader(String key, Object loadBalanceKey);

    public abstract String getRemoteIp(Object loadBalanceKey);
}
